﻿using HirelSeriesH.Entity;
using HirelSeriesH.Tools;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace HirelSeriesH.Global
{
    class AutoRun
    {
        /// <summary>
        /// 定时发送高压电源命令
        /// </summary>
        private static Timer timerToHighPower = new Timer();

        private static System.Timers.Timer timerCheckTemperature = new System.Timers.Timer();

        private static System.Timers.Timer timerReadData = new System.Timers.Timer();

        public static Timer TimerCheckTemperature { get => timerCheckTemperature; set => timerCheckTemperature = value; }
        public static Timer TimerReadData { get => timerReadData; set => timerReadData = value; }

        public static void start()
        {
            //定时查询温箱温度
            TimerCheckTemperature.AutoReset = true;
            TimerCheckTemperature.Enabled = false;
            TimerCheckTemperature.Elapsed += new ElapsedEventHandler(TimerTemperatureTask);
            TimerCheckTemperature.Interval = Global.CurrenTemperatureInterval;
            TimerCheckTemperature.Start();

            //自动查询电源的输出电压、电流
            foreach (var power in Global.PowerList)
            {
                power.TimerForLowPowerRealVC.Start();
            }
            //三色灯开始工作
            System.Threading.Thread threadAutoRun = new System.Threading.Thread(new System.Threading.ThreadStart(ThreeColor.start));
            threadAutoRun.Start();

            //TimerReadData.AutoReset = true;
            //TimerReadData.Enabled = false;
            //TimerReadData.Elapsed += new ElapsedEventHandler(readData_Tick);
            //TimerReadData.Interval = 1600;
            //TimerReadData.Start();
        }

        public static void stop()
        {
            TimerReadData.Stop();
            TimerCheckTemperature.Stop();
            foreach (var power in Global.PowerList)
            {
                power.TimerForLowPowerRealVC.Stop();
            }
            ThreeColor.IsRun = false;
        }

        public static void TimerTemperatureTask(object source, ElapsedEventArgs e)
        {
            if (Global.BoxPort == null || !Global.BoxPort.IsOpen)
            {
                Global.PtcBox.IsError = true;
                return;
            }
            else
            {
                Global.PtcBox.IsError = false;
            }

            //查询温箱当前的实际温度
            string strCommand = "C2" + "\r\n";
            string strRecieve = "";
            Global.BoxPort.DiscardInBuffer();
            Global.BoxPort.Write(strCommand);

            try
            {
                for (int i = 0; i < 20; i++)
                {
                    System.Threading.Thread.Sleep(10);
                    strRecieve += Global.BoxPort.ReadExisting();
                    if (strRecieve.IndexOf("\n") >= 0) break;
                }

                if (strRecieve == null || strRecieve.Replace("\n", "") == "")
                {
                    Global.PtcBox.IsError = true;
                    return;
                }
                else
                {
                    Global.PtcBox.IsError = false;
                }

                strRecieve = strRecieve.Replace("\n", "");
                if (strRecieve.Contains("MN"))
                {
                    Debug.Write(strRecieve);
                    string[] split = strRecieve.Split(' ');
                    for (int i = 0; i < split.Length; i++)
                    {
                        Debug.WriteLine(i.ToString() + ":" + split[i]);
                    }
                    if (split.Length < 8)
                    {
                        return;
                    }
                    Global.CurrenTemperatureStr = decimal.Parse(split[3]).ToString();

                    if (split[10].Contains("RUN"))
                    {
                        Global.CurrenBoxStutas = "运行中";
                        Global.PtcBox.Status = "RUN";
                        Global.PtcBox.Runned = true;

                        /*string tempStatus = Global.PtcBox.Status;
                        Global.PtcBox.Status = "RUN";
                        if (tempStatus == "STP")
                        {
                            Global.PtcBox.Runned = true;
                        }*/
                    }
                    if (split[10].Contains("STP"))
                    {
                        if (Global.PtcBox.Status == "RUN")
                        {
                            Global.PtcBox.IsOpen = false;
                            Global.ValueBoxRunning = false;
                        }
                        Global.CurrenBoxStutas = "停止中";
                        Global.PtcBox.Status = "STP";
                    }
                    if (split[10].Contains("ALM"))
                    {
                        Global.CurrenBoxStutas = "异常中";
                    }
                    if (split[9] != "0")
                    {
                        string[] ss = split[5].Split(':');
                        int yjyx = int.Parse(ss[0]);
                        int syzq = ((int)Global.PtcBox.TestCycs) - yjyx;
                        if (syzq < 0)
                        {
                            syzq = 0;
                        }
                        Global.Syzq = syzq.ToString();
                    }
                    else
                    {
                        if (split[10].Contains("STP"))
                        {
                            Global.Syzq = "";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.StackTrace);
            }

        }

        private static void readData_Tick(object sender, EventArgs e)
        {
            try
            {
                byte[] Command = CheckWorker.ADD(new byte[] { 0xAA, 0xB0, 0x04, 0x00, 0x28 },true);
                Global.ChannelPort.Read(Global.ChannelPort.GetNumToRead());
                Global.ChannelPort.Write(Command);
                //Thread.Sleep(100);
                for (int i = 0; i < 5; i++)
                {
                    System.Threading.Thread.Sleep(25);
                    if (Global.ChannelPort.GetNumToRead() == 165)
                    {
                        break;
                    }
                }

                byte[] DataBuffer = Global.ChannelPort.Read(165);
                if (DataBuffer.Length == 0 || DataBuffer.Length != 165)
                {
                    return;
                }

                byte[] ReceiveBytes = DataBuffer;

                string returnStr = "";
                for (int i = 0; i < ReceiveBytes.Length; i++)
                {
                    returnStr += ReceiveBytes[i].ToString("X2") + "  ";
                }
                Debug.WriteLine("接收的全部数据：" + ReceiveBytes.Length + "-->" + returnStr);

                byte[] data = new byte[ReceiveBytes.Length - 5];
                for (int i = 4; i < ReceiveBytes.Length - 1; i++)
                {
                    data[i - 4] = ReceiveBytes[i];
                }

                //插板检测
                int start = 128;
                for (int i = 0; i < 8; i++)
                {
                    decimal num = 1000;
                    byte bFlag = data[start + 1];
                    string strFlag = bFlag.ToString("X2");

                    if (strFlag == "00")
                    {
                        num = 1000;
                    }
                    else if (strFlag == "01")
                    {
                        num = 100;
                    }
                    else if (strFlag == "02")
                    {
                        num = 10;
                    }
                    else if (strFlag == "03")
                    {
                        num = 1;
                    }
                    byte bOne = data[start + 2];
                    byte btow = data[start + 3];
                    byte[] bb = { bOne, btow };
                    string bbStr = "";
                    for (int n = 0; n < bb.Length; n++)
                    {
                        bbStr += bb[n].ToString("X2");
                    }
                    short intValue = Convert.ToInt16(bbStr, 16);
                    decimal dataValue = decimal.Parse(intValue.ToString());
                    decimal num2_5 = 2.5m;
                    decimal num32768 = 32768;
                    //IR(A)
                    decimal IR;
                    IR = dataValue / num * num2_5 / num32768 / Global.ChannelList[0].CYDZ;

                    Debug.WriteLine("插板检测" + (i + 1) + "读取值(mA)：" + IR * 1000);

                    double DLYZ = 1.0;
                    double irm = (double)(IR * 1000);
                    if (irm > DLYZ)
                    {
                        Global.FlagButtons[i] = true;
                    }
                    else
                    {
                        Global.FlagButtons[i] = false;
                    }

                    start = start + 4;
                }

                //数据解析
                start = 0;
                for (int i = 0; i < Global.DataIRList.Count; i++)
                {
                    int chIndex = i / Global.ChannelList[0].Positions.Count;
                    int pIndex = i % Global.ChannelList[0].Positions.Count;

                    decimal num = 1000;
                    byte bFlag = data[start + 1];
                    string strFlag = bFlag.ToString("X2");
                    decimal GWJZ_K = 1;
                    decimal GWJZ_B = 0;
                    if (strFlag == "00")
                    {
                        num = 1000;
                        GWJZ_K = Global.ChannelList[chIndex].Positions[pIndex].GWJZ1000_K;
                        GWJZ_B = Global.ChannelList[chIndex].Positions[pIndex].GWJZ1000_B;
                    }
                    else if (strFlag == "01")
                    {
                        num = 100;
                        GWJZ_K = Global.ChannelList[chIndex].Positions[pIndex].GWJZ100_K;
                        GWJZ_B = Global.ChannelList[chIndex].Positions[pIndex].GWJZ100_B;
                    }
                    else if (strFlag == "02")
                    {
                        num = 10;
                        GWJZ_K = Global.ChannelList[chIndex].Positions[pIndex].GWJZ10_K;
                        GWJZ_B = Global.ChannelList[chIndex].Positions[pIndex].GWJZ10_B;
                    }
                    else if (strFlag == "03")
                    {
                        num = 1;
                        GWJZ_K = Global.ChannelList[chIndex].Positions[pIndex].GWJZ1_K;
                        GWJZ_B = Global.ChannelList[chIndex].Positions[pIndex].GWJZ1_B;
                    }
                    byte bOne = data[start + 2];
                    byte btow = data[start + 3];
                    byte[] bb = { bOne, btow };
                    string bbStr = "";
                    for (int n = 0; n < bb.Length; n++)
                    {
                        bbStr += bb[n].ToString("X2");
                    }
                    short intValue = Convert.ToInt16(bbStr, 16);
                    decimal dataValue = decimal.Parse(intValue.ToString());
                    decimal num2_5 = 2.5m;
                    decimal num32768 = 32768;
                    //IR(A)
                    decimal IR;
                    IR = dataValue / num * num2_5 / num32768 / Global.ChannelList[0].CYDZ;

                    Debug.WriteLine("电流" + (i + 1) + "读取值(mA)：" + IR * 1000);
                    Debug.WriteLine("电流" + (i + 1) + "基础值(mA)：" + Global.ChannelList[chIndex].Positions[pIndex].BasicValue);

                    if (IR < 0)
                    {
                        IR = 0;
                    }
                    //IR = IR * GWJZ_K + (GWJZ_B / 1000000);
                    IR = Math.Round(IR * 1000, 3);//转换成毫安
                    decimal tempIR = IR - Global.ChannelList[chIndex].Positions[pIndex].BasicValue;

                    Debug.WriteLine("电流" + (i + 1) + "输出值(mA)：" + tempIR);

                    if (tempIR < 0)
                    {
                        tempIR = 0;
                    }
                    tempIR = tempIR / 16m;
                    tempIR = tempIR * 10;

                    if (tempIR > 0.45m)
                    {
                        tempIR = tempIR * GWJZ_K + (GWJZ_B / 1000);//B为毫安
                    }
                    if (tempIR > 10)
                    {
                        tempIR = 10;
                    }

                    Debug.WriteLine("电流" + (i + 1) + "最终值(mA)：" + Math.Round(tempIR, 3));

                    if (Global.FlagButtons[chIndex])
                    {
                        if (Global.ChannelList[chIndex].Positions[pIndex].IsUse)
                        {
                            Global.DataIRList[i] = Math.Round(tempIR, 3);
                        }
                        else
                        {
                            Global.DataIRList[i] = 0;
                        }
                    }
                    else
                    {
                        Global.DataIRList[i] = 0;
                    }

                    start = start + 4;
                }
                readVolt_Power();
            }
            catch (Exception ex)
            {
                string str;
                string strDateInfo = DateTime.Now.ToString() + " 出现应用程序未处理的异常：" + "\r\n";

                if (ex != null)
                {
                    str = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n异常信息：{2}\r\n",
                         ex.GetType().Name, ex.Message, ex.StackTrace);
                }
                else
                {
                    str = string.Format("应用程序线程错误:{0}", ex);
                }
                Program.WriteLog(str);
            }
        }
        private static void readVolt()
        {
            //try
            //{
            //    byte[] Command = CheckWorker.ADD(new byte[] { 0xAA, 0xB0, 0x24, 0x00, 0x00, 0x00, 0x00 }, true);
            //    Global.VoltPort.DiscardInBuffer();
            //    Global.VoltPort.Write(Command, 0, Command.Length);
            //    //Thread.Sleep(100);
            //    for (int i = 0; i < 5; i++)
            //    {
            //        System.Threading.Thread.Sleep(25);
            //        if (Global.VoltPort.BytesToRead == 101)
            //        {
            //            break;
            //        }
            //    }
            //    if (Global.VoltPort.BytesToRead == 0 || Global.VoltPort.BytesToRead != 101)
            //    {
            //        return;
            //    }
            //    byte[] DataBuffer = new byte[Global.VoltPort.BytesToRead];
            //    Global.VoltPort.Read(DataBuffer, 0, DataBuffer.Length);

            //    byte[] ReceiveBytes = DataBuffer;

            //    string returnStr = "";
            //    for (int i = 0; i < ReceiveBytes.Length; i++)
            //    {
            //        returnStr += ReceiveBytes[i].ToString("X2") + "  ";
            //    }
            //    //Debug.WriteLine("接收的全部电压数据：" + ReceiveBytes.Length + "-->" + returnStr);

            //    byte[] data = new byte[ReceiveBytes.Length - 5];
            //    for (int i = 4; i < ReceiveBytes.Length - 1; i++)
            //    {
            //        data[i - 4] = ReceiveBytes[i];
            //    }

            //    int start = 0;
            //    for (int i = 0; i < Global.DataVoltList.Count; i++)
            //    {
            //        int chIndex = i / Global.ChannelList[0].Positions.Count;
            //        int pIndex = i % Global.ChannelList[0].Positions.Count;

            //        byte bOne = data[start];
            //        byte btow = data[start + 1];
            //        byte[] bb = { bOne, btow };
            //        string bbStr = "";
            //        for (int n = 0; n < bb.Length; n++)
            //        {
            //            bbStr += bb[n].ToString("X2");
            //        }
            //        short intValue = Convert.ToInt16(bbStr, 16);
            //        decimal dataValue = decimal.Parse(intValue.ToString());

            //        if (dataValue > 32767)
            //        {
            //            dataValue = dataValue - 65536;//负数处理
            //        }
            //        decimal volt = dataValue / 32768.0m * 5;
            //        //Debug.WriteLine("电压" + (i + 1) + "计算值(V)：" + Math.Round(volt, 3));
            //        if (volt < 0)
            //        {
            //            volt = 0;
            //        }
            //        decimal GWJZ_K = Global.ChannelList[chIndex].Positions[pIndex].VoltK;
            //        decimal GWJZ_B = Global.ChannelList[chIndex].Positions[pIndex].VoltB;
            //        volt = volt * GWJZ_K + GWJZ_B;//校准值
            //        //Debug.WriteLine("电压" + (i + 1) + "校准值(V)：" + Math.Round(volt, 3));

            //        volt = volt * Global.ChannelList[chIndex].Positions[pIndex].FDBS;//放大倍数
            //        //Debug.WriteLine("电压" + (i + 1) + "最终值(V)：" + Math.Round(volt, 3));

            //        if (Global.FlagButtons[chIndex])
            //        {
            //            Global.DataVoltList[i] = Math.Round(volt, 3);
            //        }
            //        else
            //        {
            //            Global.DataVoltList[i] = 0;
            //        }

            //        start = start + 2;
            //    }

            //}
            //catch (Exception ex)
            //{
            //    string str;
            //    string strDateInfo = DateTime.Now.ToString() + " 出现应用程序未处理的异常：" + "\r\n";

            //    if (ex != null)
            //    {
            //        str = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n异常信息：{2}\r\n",
            //             ex.GetType().Name, ex.Message, ex.StackTrace);
            //    }
            //    else
            //    {
            //        str = string.Format("应用程序线程错误:{0}", ex);
            //    }
            //    Program.WriteLog(str);
            //}
        }
        private static void readVolt_Power()
        {
            try
            {
                for (int i = 0; i < Global.DataVoltList.Count; i++)
                {
                    int chIndex = i / Global.ChannelList[0].Positions.Count;
                    int pIndex = i % Global.ChannelList[0].Positions.Count;

                    Power nowPower = Global.PowerList[pIndex];

                    decimal volt = nowPower.RealVoltage;



                    if (Global.FlagButtons[chIndex])
                    {
                        if (Global.ChannelList[chIndex].Positions[pIndex].IsUse)
                        {
                            Global.DataVoltList[i] = Math.Round(volt, 3);
                        }
                        else
                        {
                            Global.DataVoltList[i] = 0;
                        }
                    }
                    else
                    {
                        Global.DataVoltList[i] = 0;
                    }
                }


            }
            catch (Exception ex)
            {
                string str;
                string strDateInfo = DateTime.Now.ToString() + " 出现应用程序未处理的异常：" + "\r\n";

                if (ex != null)
                {
                    str = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n异常信息：{2}\r\n",
                         ex.GetType().Name, ex.Message, ex.StackTrace);
                }
                else
                {
                    str = string.Format("应用程序线程错误:{0}", ex);
                }
                Program.WriteLog(str);
            }
        }

    }
}
